/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-03-24 14:52:38
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-03-26 16:09:27
 * @FilePath: /code/lesson25/named_pipe/PipeServer.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "Comm.hpp"

//为什么要server读，client写，为什么管道要由读端来创建
//client：写，server：读
int main()
{
    Fifo fifo(Path);//管道运行时创建

    int rfd = open(Path, O_RDONLY);
    if(rfd < 0)
    {
        cerr << "open failed " << errno << " errstring: " << strerror(errno) << endl;
        return 1;
    }

    //当写端未打开时，此处读端open时会阻塞住，直至写端打开，读端open才会返回
    cout << "open success" << endl;

    char buf[1024];
    while(true)
    {
        int n = read(rfd, buf, sizeof(buf) - 1);
        if(n > 0)
        {
            buf[n] = 0;
            cout << "client say: " << buf << endl;
        }
        else if(n == 0)
        {
            cout << "client quit, me too!" << endl;
            break;
        }
        else
        {
            cerr << "read failed " << errno << " errstring: " << strerror(errno) << endl;
            break;
        }
    }

    close(rfd);

    return 0;
}